<?php defined('BASEPATH') OR exit('No direct script access allowed');
/**
 * Description:
 *
 * @author      Eden
 * @datetime    2016/12/17 15:31
 * @copyright   Beijing CmsTop Technology Co.,Ltd.
 */

class Express_Model extends ADM_Model
{
    /**
     * 初始化
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 获取
     * @return bool
     */
    public function getSetting()
    {
        $db = clone($this->db);
        $q = $db->join('express_weight as ew', 'ew.tmpId = et.id')->get('express_template as et');
        $res = $q->row_array();
        if (empty($res)) {
            return false;
        }

        return $res;
    }

    /**
     * 设置
     * @param $params
     * @return bool
     */
    public function setSetting($params)
    {

        $expressSettingDb = clone($this->db);
        $eData = array(
            'tmpName' => $params['tmpName'],
            'dispatchAddr' => $params['dispatchAddr'],
            'payer' => $params['payer'],
            'payType' => $params['count']['countType']
        );
        $lists = $params['count']['lists'][0];
        $wData = array(
            'area' => $lists['area'],
            'firstWeight' => $lists['firstWeight'],
            'firstCost' => $lists['firstCost'],
            'incrWeight' => $lists['incrWeight'],
            'incrCost' => $lists['incrCost']
        );

        $q = $expressSettingDb->get('express_template');
        if ($row = $q->row_array()) {
            // yes
            $id = $row['id'];
            $expressSettingDb->trans_start();
            $sdb = clone($this->db);

            $sdb->where('id', $id);
            $sdb->update('express_template', $eData);
            $wDb = clone($this->db);

            $wDb->where('tmpId', $id);
            $wDb->update('express_weight', $wData);
            $expressSettingDb->trans_complete();
            if ($expressSettingDb->trans_status() === false) {
                return false;
            }
            return true;
        } else {

            $expressSettingDb->trans_start();
            $edb = clone($this->db);
            $edb->insert('express_template', $eData);
            $id = $edb->insert_id();
            $wData = array_merge($wData, array('tmpId' => $id));
            $wDb = clone($this->db);
            $wDb->insert('express_weight', $wData);
            $expressSettingDb->trans_complete();
            if($expressSettingDb->trans_status() == true) {
                return true;
            }
            return false;
        }
    }
}
